const { customerModel } = require('../modules/customer')

//新增客户
async function addCustomer(req, res, next) {
    const data = req.body;
    const result = await customerModel.create(data);
    if (result) {
        res.send({
            message: "添加客户成功",
            code: 200
        });
    } else {
        res.send({
            message: "添加客户失败",
            code: 500
        });
    }

}


//修改客户
async function updateCustomer(req, res, next) {
    const data = req.body;
    const _id = data._id;
    const result = await customerModel.updateOne({ _id }, data);
    if (result.ok > 0) {
        res.send({
            message: "修改客户信息成功",
            code: 200
        });
    } else {
        res.send({
            message: "修改客户信息失败",
            code: 500
        });
    }

}



//获取客户数据
async function getCustomer(req, res, next) {
    const data = req.query;
    const value = data.searchObj.value;
    const currentPage = data.currentPage;
    const pageSize = data.pageSize;
    const result = await customerModel
        .find({ $or: [{ name: { $regex: value, $options: '$i' } }, { tel: { $regex: value, $options: '$i' } }] })
        .limit(Number(pageSize))
        .skip((Number(currentPage) - 1) * Number(pageSize));
    const total = await customerModel
        .find({ $or: [{ name: { $regex: value, $options: '$i' } }, { tel: { $regex: value, $options: '$i' } }] })
        .countDocuments();
    const pages = Math.ceil(total / pageSize);
    if (result.length > 0) {
        res.send({
            message: "获取客户数据成功",
            code: 200,
            result,
            total,
            pages
        });
    } else {
        res.send({
            message: "获取客户数据失败",
            code: 500
        });
    }
}


//通过ID获取客户数据
async function getCustomerById(req, res, next) {
    const _id = req.params;
    const result = await customerModel.find({ _id });
    if (result.length > 0) {
        res.send({
            message: "获取客户数据成功",
            code: 200,
            result: result[0]
        });
    } else {
        res.send({
            message: "获取客户数据失败",
            code: 500
        });
    }
}




//删除客户数据
async function delCustomer(req, res, next) {
    const data = req.body;
    const result = await customerModel.deleteOne(data);
    if (result.deletedCount > 0) {
        res.send({
            message: "删除客户数据成功",
            code: 200,
        });
    } else {
        res.send({
            message: "删除客户数据失败",
            code: 500
        });
    }

}



module.exports = {
    addCustomer, getCustomer, delCustomer, getCustomerById, updateCustomer
}